import { CSSProperties, useState } from 'react'
import classNames from 'classnames'
import { Avatar, Popover, Tag } from 'antd'
import Icon from '@ant-design/icons'

import { Texty } from '@/components/Texty'
import { addAvatarOSSParams } from '@/utils/utils'
import AvatarIcon from '@/assets/icons/avatar.svg?react'
import styles from './styles.module.less'

interface IData {
  /**
   * 头像
   * @default `@/assets/icons/avatar.svg`
   */
  avatar?: string | null
  /** 名称 */
  name?: string | null
  /** 标签 */
  tagName?: string | null
  /** 电话 */
  phone?: string | null
}

export interface IUserProps {
  style?: CSSProperties
  className?: string
  /** @default 33 */
  itemSize?: number
  data: IData
}

export interface IUsersProps {
  style?: CSSProperties
  className?: string
  /** @default 33 */
  itemSize?: number
  dataList: IData[]
}

/** 单个用户 */
export const User = ({ style, className, itemSize, data }: IUserProps) => {
  const avatar = addAvatarOSSParams(data.avatar)
  const { name, tagName, phone } = data
  const [vis, setVis] = useState(false)
  return (
    <Popover
      destroyTooltipOnHide
      open={vis}
      onOpenChange={setVis}
      content={
        <div className={styles.tip}>
          <Avatar className={styles.tip_left} size="large" src={avatar || <Icon component={AvatarIcon} />} />
          {!!name && !!tagName && !!phone && (
            <div className={styles.tip_right}>
              {!!name && !!tagName && (
                <div className={styles.tip_right_top}>
                  {!!name && <Texty className={styles.tip_right_top_name}>{name}</Texty>}
                  {!!tagName && <Tag className={styles.tip_right_top_tag}>{tagName}</Tag>}
                </div>
              )}
              {!!phone && <Texty className={styles.tip_right_bottom}>{phone}</Texty>}
            </div>
          )}
        </div>
      }
    >
      <Avatar
        style={{ width: itemSize || 33, height: itemSize || 33, zIndex: vis ? 1 : undefined, ...style }}
        className={classNames(styles.User, className)}
        src={avatar || <Icon component={AvatarIcon} />}
      />
    </Popover>
  )
}

/** 多个用户 */
export const Users = ({ dataList, ...rest }: IUsersProps) => {
  const { style, className } = rest
  return (
    <div style={style} className={classNames(styles.Users, className)}>
      {dataList.map((d, i) => (
        <User key={[d.avatar, d.name, d.tagName, d.phone, i + 1].filter(Boolean).join('_')} data={d} {...rest} />
      ))}
    </div>
  )
}
